package org.boticelli.util;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;
import org.svenson.JSON;
import org.svenson.JSONable;

/**
 * JSON-View Implementierung. Wandelt ein Java-Datenmodell in JSON Datan um.
 * Kann auf Wunsch auch den JSON output mit gzip komprimieren.
 * @see JSON
 * @see JSONable
 * @author shelmberger
 */
public class JSONView implements View
{
    private Object model;
    private boolean compress;

    public JSONView(Object model)
    {
        this.model=model;
    }

    public JSONView(Object model, boolean compress)
    {
        this.model=model;
        this.compress=compress;
    }


    public void render(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        String json=JSON.defaultJSON(). dumpObjectFormatted( this.model);
        byte[] data = json.getBytes(response.getCharacterEncoding());
        GzippedResponseUtil.sendResponse(request, response, data, compress);
    }

    public static ModelAndView modelAndView(Object model)
    {
        return new ModelAndView(new JSONView(model));
    }

    public static ModelAndView modelAndView(Object model, boolean compress)
    {
        return new ModelAndView(new JSONView(model,compress));
    }

    public String getContentType()
    {
        return "application/json";
    }
}
